package com.petcommunity.servlet;

import com.petcommunity.dao.OwnerDAO;
import com.petcommunity.model.Owner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/owners")
public class OwnerServlet extends HttpServlet {

    private OwnerDAO ownerDAO = new OwnerDAO();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Owner> owners = ownerDAO.getAllOwners();
        System.out.println("Owners fetched from database: " + owners);
        request.setAttribute("owners", owners);
        request.getRequestDispatcher("owners.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");


        Owner owner = new Owner();
        owner.setName(request.getParameter("name"));
        owner.setPhone(request.getParameter("phone"));
        owner.setAddress(request.getParameter("address"));

        ownerDAO.addOwner(owner);
        response.sendRedirect("owners");
    }
}
